using Godot;
using System;

public partial class MetaUpgradeCard : PanelContainer
{

	private Label nameLable;
	private Label descriptionLable;

	ProgressBar progressBar;
	MetaUpgrade upgrade;
	MetaProgression metaProgression;
	Button purchaseButton;
	Label progressLabel;
	Label countLabel;
	

	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		nameLable = GetNode<Label>("%NameLable");
		descriptionLable = GetNode<Label>("%DescriptionLable");
		progressBar = GetNode<ProgressBar>("%ProgressBar");
		metaProgression = GetNode<MetaProgression>("/root/MetaProgression");
		purchaseButton = GetNode<Button>("%PurchaseButton");
		progressLabel = GetNode<Label>("%ProgressLabel");
		countLabel = GetNode<Label>("%CountLabel");

		GuiInput += OnGuiInput;
		purchaseButton.Pressed += OnPurchasePressed;
	}


	public void SetMetaUpgrade(MetaUpgrade upgrade){
		this.upgrade = upgrade;
		nameLable.Text = upgrade.title;
		descriptionLable.Text = upgrade.description;
		this.UpdateProgress();
	}

	public void UpdateProgress(){
		int currentQuantity = 0;
		if(metaProgression.saveData["metaUpgrades"].AsGodotDictionary<string, Variant>().ContainsKey(upgrade.id)){
			currentQuantity = (int)metaProgression.saveData["metaUpgrades"].AsGodotDictionary<string, Variant>()[upgrade.id].AsGodotDictionary()["quantity"];
		}
		var isMax = currentQuantity >= upgrade.maxQuantity;
		int currency = metaProgression.saveData["metaUpgradeCurrency"].AsInt32();
		double percent = (double)currency/upgrade.experienceCost;
		percent = Math.Min(percent,1);
		progressBar.Value = percent;
		purchaseButton.Disabled = percent<1 || isMax; 
		if(isMax){
			purchaseButton.Text = "Max ";
		}
		progressLabel.Text = currency + "/" + upgrade.experienceCost;
		countLabel.Text = string.Format("x{0}",currentQuantity);
	}

	public void SelectCard(){
		GetNode<AnimationPlayer>("AnimationPlayer").Play("selected");
	}

	public void OnGuiInput(InputEvent @event){
		if( @event.IsActionPressed("left_click",false,false)){
			SelectCard();
		}
	}

	public void OnPurchasePressed(){
		if(upgrade == null){
			return ;
		}
		metaProgression.saveData["metaUpgradeCurrency"] = metaProgression.saveData["metaUpgradeCurrency"].AsInt32() - upgrade.experienceCost;
		metaProgression.AddMetaUpgrade(upgrade);

		this.UpdateProgress();
		GetTree().CallGroup("meta_upgrade_card","UpdateProgress");
		GetNode<AnimationPlayer>("AnimationPlayer").Play("selected");
	}

}
